<!DOCTYPE html>
<html>
<head>
    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?a7c05ce530152d9866930ef4850ee566"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    
    
    
    <title>Mybatis快速入门二(DAO开发思路) | 神奇的鸭鸭の码农库 | 新知识要不断的总结记录成笔记，要多写，多画，能够清晰透彻的将知识讲给别人听，才是达到理解的层次。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#765959">
    
    
    <meta name="keywords" content="SSM">
    <meta name="description" content="mybatis与hibernate的区别及各自应用场景：mybatis技术特点适合需求多变的互联网项目  1 通过直接编写SQL语句，可以直接对SQL进行性能的优化。 2 学习门槛低，周期短，只要有SQL基础基本可以2天只能快速上手应用。 3 由于直接编写SQL语句，所以灵活多变，代码维护性更好。 4 不能支持数据库无关性，即数据库发生变更，要写多套代码进行支持，移植性较差。 5 需要编写结果映射">
<meta name="keywords" content="SSM">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis快速入门二(DAO开发思路)">
<meta property="og:url" content="http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/index.html">
<meta property="og:site_name" content="神奇的鸭鸭の码农库">
<meta property="og:description" content="mybatis与hibernate的区别及各自应用场景：mybatis技术特点适合需求多变的互联网项目  1 通过直接编写SQL语句，可以直接对SQL进行性能的优化。 2 学习门槛低，周期短，只要有SQL基础基本可以2天只能快速上手应用。 3 由于直接编写SQL语句，所以灵活多变，代码维护性更好。 4 不能支持数据库无关性，即数据库发生变更，要写多套代码进行支持，移植性较差。 5 需要编写结果映射">
<meta property="og:updated_time" content="2017-12-05T09:57:56.343Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Mybatis快速入门二(DAO开发思路)">
<meta name="twitter:description" content="mybatis与hibernate的区别及各自应用场景：mybatis技术特点适合需求多变的互联网项目  1 通过直接编写SQL语句，可以直接对SQL进行性能的优化。 2 学习门槛低，周期短，只要有SQL基础基本可以2天只能快速上手应用。 3 由于直接编写SQL语句，所以灵活多变，代码维护性更好。 4 不能支持数据库无关性，即数据库发生变更，要写多套代码进行支持，移植性较差。 5 需要编写结果映射">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">神奇的鸭鸭</h5>
          <a href="mailto:702038338@qq.com" title="702038338@qq.com" class="mail">702038338@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/magic_duck" target="_blank" >
                <i class="icon icon-lg icon-gg-circle"></i>
                码云
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.zhihu.com/people/shen-qi-de-ya-ya" target="_blank" >
                <i class="icon icon-lg icon-twitter"></i>
                知乎
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">Mybatis快速入门二(DAO开发思路)</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">Mybatis快速入门二(DAO开发思路)</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-08-13T04:55:00.000Z" itemprop="datePublished" class="page-time">
  2017-08-13
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#mybatis与hibernate的区别及各自应用场景："><span class="post-toc-number">1.</span> <span class="post-toc-text">mybatis与hibernate的区别及各自应用场景：</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#mybatis技术特点"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">mybatis技术特点</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Hibernate技术特点："><span class="post-toc-number">1.2.</span> <span class="post-toc-text">Hibernate技术特点：</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#mybatis开发dao"><span class="post-toc-number">2.</span> <span class="post-toc-text">mybatis开发dao</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#原始dao开发方式"><span class="post-toc-number">3.</span> <span class="post-toc-text">原始dao开发方式</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#思路"><span class="post-toc-number">3.1.</span> <span class="post-toc-text">思路</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#省略步骤1-2-3-4"><span class="post-toc-number">3.2.</span> <span class="post-toc-text">省略步骤1,2,3,4</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#dao接口"><span class="post-toc-number">3.3.</span> <span class="post-toc-text">dao接口</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#dao实现类"><span class="post-toc-number">3.4.</span> <span class="post-toc-text">dao实现类</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#测试类"><span class="post-toc-number">3.5.</span> <span class="post-toc-text">测试类</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#问题总结"><span class="post-toc-number">3.6.</span> <span class="post-toc-text">问题总结</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Mapper代理开发方式"><span class="post-toc-number">4.</span> <span class="post-toc-text">Mapper代理开发方式</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Mapper代理的开发规范"><span class="post-toc-number">4.1.</span> <span class="post-toc-text">Mapper代理的开发规范</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#思路-1"><span class="post-toc-number">4.2.</span> <span class="post-toc-text">思路</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#省略步骤1-2"><span class="post-toc-number">4.3.</span> <span class="post-toc-text">省略步骤1,2</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#mapper接口"><span class="post-toc-number">4.4.</span> <span class="post-toc-text">mapper接口</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#mapper映射文件"><span class="post-toc-number">4.5.</span> <span class="post-toc-text">mapper映射文件</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#加载映射文件"><span class="post-toc-number">4.6.</span> <span class="post-toc-text">加载映射文件</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#编写mapper接口"><span class="post-toc-number">4.7.</span> <span class="post-toc-text">编写mapper接口</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#测试代码"><span class="post-toc-number">4.8.</span> <span class="post-toc-text">测试代码</span></a></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-Mybatis_primary_02"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">Mybatis快速入门二(DAO开发思路)</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年08月13日 12:55" datetime="2017-08-13T04:55:00.000Z"  itemprop="datePublished">2017-08-13</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h2 id="mybatis与hibernate的区别及各自应用场景："><a href="#mybatis与hibernate的区别及各自应用场景：" class="headerlink" title="mybatis与hibernate的区别及各自应用场景："></a>mybatis与hibernate的区别及各自应用场景：</h2><h3 id="mybatis技术特点"><a href="#mybatis技术特点" class="headerlink" title="mybatis技术特点"></a>mybatis技术特点</h3><p>适合需求多变的互联网项目</p>
<ul>
<li>1 通过直接编写SQL语句，可以直接对SQL进行性能的优化。</li>
<li>2 学习门槛低，周期短，只要有SQL基础基本可以2天只能快速上手应用。</li>
<li>3 由于直接编写SQL语句，所以灵活多变，代码维护性更好。</li>
<li>4 不能支持数据库无关性，即数据库发生变更，要写多套代码进行支持，移植性较差。</li>
<li>5 需要编写结果映射。</li>
</ul>
<h3 id="Hibernate技术特点："><a href="#Hibernate技术特点：" class="headerlink" title="Hibernate技术特点："></a>Hibernate技术特点：</h3><p>适合需求明确，业务固定的项目，例如OA项目，ERP项目等。</p>
<ul>
<li>1 标准的ORM框架，程序员不需要编写SQL语句</li>
<li>2 具有良好的数据库无关性，即数据库发生变化的话，代码无需再次编写。</li>
<li>3 学习门槛高，周期长，需要对数据库关系模型有良好基础，而且在设置ORM映射的时候，需要考虑好性能和对象模型的权衡。</li>
<li>4 初级上手的程序员不能自主的去进行SQL性能优化。</li>
<li>5 使用不好可能适得其反，影响性能和效率。</li>
</ul>
<hr>
<h2 id="mybatis开发dao"><a href="#mybatis开发dao" class="headerlink" title="mybatis开发dao"></a>mybatis开发dao</h2><p>mybatis在项目中主要使用的地方就是开发dao(数据访问层)，所以本文讲解mybatis开发dao的两种方式：</p>
<ul>
<li>原始dao开发方式</li>
<li>mapper代理开发方式 <strong>(推荐方式)</strong></li>
</ul>
<h2 id="原始dao开发方式"><a href="#原始dao开发方式" class="headerlink" title="原始dao开发方式"></a>原始dao开发方式</h2><h3 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h3><p>以往开发dao基本思路：需要编写dao接口和dao实现类，基本流程如下：</p>
<ul>
<li>1 根据需求创建po类</li>
<li>2 编写全局配置文件</li>
<li>3 根据需求编写映射文件</li>
<li>4 加载映射文件</li>
<li>5 编写dao接口</li>
<li>6 编写dao实现类</li>
<li>7 编写测试代码</li>
</ul>
<h3 id="省略步骤1-2-3-4"><a href="#省略步骤1-2-3-4" class="headerlink" title="省略步骤1,2,3,4"></a>省略步骤1,2,3,4</h3><p>步骤中的1、2、3、4都在 <strong>Mybatis快速入门一(基本应用)</strong> 中进行了编写，此处不再进行描述，建议你先阅读 <strong>Mybatis快速入门一(基本应用)</strong> 了解SqlSession、SqlSessionFactory、SqlSessionFactoryBuilder各自的生命周期后再来阅读本文。</p>
<h3 id="dao接口"><a href="#dao接口" class="headerlink" title="dao接口"></a>dao接口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserDao</span> </span>&#123;</div><div class="line">   </div><div class="line">   <span class="comment">// 1 根据用户ID查询用户信息</span></div><div class="line">   <span class="function"><span class="keyword">public</span> User <span class="title">findUserById</span><span class="params">(<span class="keyword">int</span> id)</span> <span class="keyword">throws</span> Exception</span>;</div><div class="line">   <span class="comment">// 2 根据用户名称模糊查询用户列表</span></div><div class="line">   <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">findUsersByName</span><span class="params">(String name)</span> <span class="keyword">throws</span> Exception</span>;</div><div class="line">   <span class="comment">// 3 添加用户</span></div><div class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insertUser</span><span class="params">(User user)</span> <span class="keyword">throws</span> Exception</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="dao实现类"><a href="#dao实现类" class="headerlink" title="dao实现类"></a>dao实现类</h3><p>由于本文介绍的是mybatis开发dao的方式，所以不涉及到spring的DI依赖注入和AOP切面编程，因此我们需要通过构造函数注入SqlSessionFactory，在方法体内通过SqlSessionFactory创建SqlSession，关闭SqlSession。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserDaoImpl</span> <span class="keyword">implements</span> <span class="title">UserDao</span> </span>&#123;</div><div class="line">    </div><div class="line">    <span class="comment">// 使用构造方法来初始化sqlSessionFactory</span></div><div class="line">    <span class="comment">// SqlSessionFactory，它的生命周期，应该是应用范围，全局范围只有一个工厂，</span></div><div class="line">    <span class="comment">// 推荐使用单例模式来实现这个功能。与spring集成之后，由spring来对其进行单例管理。</span></div><div class="line">    <span class="keyword">private</span> SqlSessionFactory sqlSessionFactory;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UserDaoImpl</span><span class="params">(SqlSessionFactory sqlSessionFactory)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.sqlSessionFactory = sqlSessionFactory;</div><div class="line">    &#125;</div><div class="line">    	</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">findUserById</span><span class="params">(<span class="keyword">int</span> id)</span> </span>&#123;</div><div class="line">        <span class="comment">// 创建SqlSession</span></div><div class="line">        <span class="comment">// SqlSession，它内部含有一块数据区域，存在线程不安全的问题，</span></div><div class="line">        <span class="comment">// 所以应该将sqlsession声明到方法内部。</span></div><div class="line">        SqlSession sqlSession = sqlSessionFactory.openSession();</div><div class="line">        User user = sqlSession.selectOne(<span class="string">"test.findUserById"</span>, id);</div><div class="line">        <span class="comment">// 关闭资源</span></div><div class="line">        sqlSession.close();</div><div class="line">        <span class="keyword">return</span> user;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">findUsersByName</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        SqlSession sqlSession = sqlSessionFactory.openSession();</div><div class="line">        List&lt;User&gt; list = sqlSession.selectList(<span class="string">"test.findUsersByName"</span>, name);</div><div class="line">        sqlSession.close();</div><div class="line">        <span class="keyword">return</span> list;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insertUser</span><span class="params">(User user)</span> </span>&#123;</div><div class="line">        SqlSession sqlSession = sqlSessionFactory.openSession();</div><div class="line">        sqlSession.insert(<span class="string">"test.insertUser"</span>, user);</div><div class="line">        sqlSession.close();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="测试类"><a href="#测试类" class="headerlink" title="测试类"></a>测试类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserDaoTest</span> </span>&#123;</div><div class="line">    </div><div class="line">    <span class="comment">// 声明全局的SqlSessionFactory</span></div><div class="line">    <span class="keyword">private</span> SqlSessionFactory SqlSessionFactory;</div><div class="line">    </div><div class="line">    <span class="meta">@Before</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUp</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">// 1 读取配置文件</span></div><div class="line">        String resource = <span class="string">"mybatis-config.xml"</span>;</div><div class="line">        InputStream inputStream = Resources.getResourceAsStream(resource);</div><div class="line">        <span class="comment">// 2 根据配置文件创建SqlSessionFactory</span></div><div class="line">        SqlSessionFactory = <span class="keyword">new</span> SqlSessionFactoryBuilder().build(inputStream);</div><div class="line">    &#125;</div><div class="line">    	</div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testFindUserById</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        UserDao userDao = <span class="keyword">new</span> UserDaoImpl(SqlSessionFactory);</div><div class="line">        User user = userDao.findUserById(<span class="number">1</span>);</div><div class="line">        System.out.println(user);</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testFindUsersByName</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        UserDao userDao = <span class="keyword">new</span> UserDaoImpl(SqlSessionFactory);</div><div class="line">        List&lt;User&gt; list = userDao.findUsersByName(<span class="string">"小明"</span>);</div><div class="line">        System.out.println(list);</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testInsertUser</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        UserDao userDao = <span class="keyword">new</span> UserDaoImpl(SqlSessionFactory);</div><div class="line">        User user = <span class="keyword">new</span> User();</div><div class="line">        user.setUsername(<span class="string">"神奇的鸭鸭2"</span>);</div><div class="line">        user.setAddress(<span class="string">"计创南300"</span>);</div><div class="line">        userDao.insertUser(user);</div><div class="line">        System.out.println(user.getId());</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="问题总结"><a href="#问题总结" class="headerlink" title="问题总结"></a>问题总结</h3><p>原始dao开发方式存在的一些问题：</p>
<ul>
<li>1 存在一定量的魔板代码，比如：通过SqlSessionFactory创建SqlSession；调用SqlSession的方法操作数据库；关闭Sqlsession，这个操作应该使用动态代理技术去完成。</li>
<li>2 存在一些硬编码问题。比如：调用SqlSession方法操作数据库时，需要指定statement的id，就存在硬编码问题。</li>
</ul>
<hr>
<h2 id="Mapper代理开发方式"><a href="#Mapper代理开发方式" class="headerlink" title="Mapper代理开发方式"></a>Mapper代理开发方式</h2><p>Mapper代理的开发方式，程序员只需要编写mapper接口（相当于dao接口）即可。Mybatis会自动的为mapper接口生成动态代理实现类，而mapper代理使用的是jdk的代理策略。</p>
<h3 id="Mapper代理的开发规范"><a href="#Mapper代理的开发规范" class="headerlink" title="Mapper代理的开发规范"></a>Mapper代理的开发规范</h3><p>要实现mapper代理的开发方式，需要遵循一些开发规范，通过规范式的开发mapper接口，可以解决原始dao开发中存在的问题。</p>
<ul>
<li>1 mapper接口的全限定名要和mapper映射文件的namespace的值相同。</li>
<li>2 mapper接口的方法名称要和mapper映射文件的statement的id相同。</li>
<li>3 mapper接口的方法参数只能有一个，且类型要和mapper映射文件中的statement的parameterType的值保持一致</li>
<li>4 mapper接口的返回值类型要和mapper映射文件中statement的resultType值或resultMap中的type值保持一致。</li>
</ul>
<h3 id="思路-1"><a href="#思路-1" class="headerlink" title="思路"></a>思路</h3><p>基本流程如下：</p>
<ul>
<li>1 根据需求创建po类</li>
<li>2 编写全局配置文件</li>
<li>3 根据需求编写映射文件</li>
<li>4 加载映射文件</li>
<li>5 编写mapper接口</li>
<li>6 编写测试代码</li>
</ul>
<h3 id="省略步骤1-2"><a href="#省略步骤1-2" class="headerlink" title="省略步骤1,2"></a>省略步骤1,2</h3><p>步骤中的1、2都在<strong>Mybatis快速入门一(基本应用)</strong>中进行了编写，此处不再进行描述。</p>
<h3 id="mapper接口"><a href="#mapper接口" class="headerlink" title="mapper接口"></a>mapper接口</h3><p>重新定义mapper映射文件UserMapper.xml。内容同Users.xml，但需要遵循mapper接口开发规范，由于我们在<strong>Mybatis快速入门一(基本应用)</strong>已经遵循了大部分规范，除了<strong>namespace</strong>的值，你只需改正它即可。另外根据mybatis的命名规范应将该文件放置到config下的mapper目录下。</p>
<h3 id="mapper映射文件"><a href="#mapper映射文件" class="headerlink" title="mapper映射文件"></a>mapper映射文件</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</div><div class="line"><span class="meta">&lt;!DOCTYPE mapper</span></div><div class="line"><span class="meta">  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"</span></div><div class="line"><span class="meta">  "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;</span></div><div class="line">  </div><div class="line"><span class="comment">&lt;!-- namespace：此时用mapper代理方式，它的值必须等于对应mapper接口的全限定类名 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">"cn.sqdyy.mybatis.mapper.UserMapper"</span>&gt;</span></div><div class="line">  <span class="comment">&lt;!-- 根据用户ID查询用户信息 --&gt;</span></div><div class="line">  <span class="comment">&lt;!-- select：表示一个MappedStatement对象 --&gt;</span></div><div class="line">  <span class="comment">&lt;!-- id：代表statement的唯一标示 --&gt;</span></div><div class="line">  <span class="comment">&lt;!-- parameterType：输入参数的java类型(可以写全限定类名) --&gt;</span></div><div class="line">  <span class="comment">&lt;!-- resultTYpe：输出结果所映射的java类型(单条结果所对应的java类型) --&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findUserById"</span> <span class="attr">parameterType</span>=<span class="string">"int"</span> <span class="attr">resultType</span>=<span class="string">"cn.sqdyy.mybatis.dao.User"</span>&gt;</span></div><div class="line">    select * from user where id = #&#123;id&#125;;</div><div class="line">  <span class="tag">&lt;/<span class="name">select</span>&gt;</span></div><div class="line">  </div><div class="line">  <span class="comment">&lt;!-- 根据用户名称模糊查询用户列表 --&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findUsersByName"</span> <span class="attr">parameterType</span>=<span class="string">"java.lang.String"</span> <span class="attr">resultType</span>=<span class="string">"cn.sqdyy.mybatis.dao.User"</span>&gt;</span></div><div class="line">    select * from user where username like '%$&#123;value&#125;%';</div><div class="line">  <span class="tag">&lt;/<span class="name">select</span>&gt;</span></div><div class="line">  </div><div class="line">  <span class="comment">&lt;!-- 添加用户 --&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">"insertUser"</span> <span class="attr">parameterType</span>=<span class="string">"cn.sqdyy.mybatis.dao.User"</span>&gt;</span></div><div class="line">  	<span class="tag">&lt;<span class="name">selectKey</span> <span class="attr">keyProperty</span>=<span class="string">"id"</span> <span class="attr">resultType</span>=<span class="string">"int"</span> <span class="attr">order</span>=<span class="string">"AFTER"</span>&gt;</span></div><div class="line">  	  select last_insert_id();</div><div class="line">  	<span class="tag">&lt;/<span class="name">selectKey</span>&gt;</span></div><div class="line">  	insert into user</div><div class="line">  	(username,birthday,sex,address)</div><div class="line">  	values(#&#123;username&#125;,#&#123;birthday&#125;,#&#123;sex&#125;,#&#123;address&#125;);</div><div class="line">  <span class="tag">&lt;/<span class="name">insert</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="加载映射文件"><a href="#加载映射文件" class="headerlink" title="加载映射文件"></a>加载映射文件</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 加载映射文件 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">mappers</span>&gt;</span></div><div class="line">  <span class="comment">&lt;!-- &lt;mapper resource="User.xml"/&gt; --&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">mapper</span> <span class="attr">resource</span>=<span class="string">"mapper/UserMapper.xml"</span>/&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="编写mapper接口"><a href="#编写mapper接口" class="headerlink" title="编写mapper接口"></a>编写mapper接口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> </span>&#123;</div><div class="line">    </div><div class="line">    <span class="comment">// 1 根据用户ID查询用户信息</span></div><div class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">findUserById</span><span class="params">(<span class="keyword">int</span> id)</span></span>;</div><div class="line">    <span class="comment">// 2 根据用户名称模糊查询用户列表</span></div><div class="line">    <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">findUsersByName</span><span class="params">(String name)</span></span>;</div><div class="line">    <span class="comment">// 3 添加用户</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insertUser</span><span class="params">(User user)</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="测试代码"><a href="#测试代码" class="headerlink" title="测试代码"></a>测试代码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserMapperTest</span> </span>&#123;</div><div class="line">    </div><div class="line">    <span class="comment">// 声明全局的SqlSessionFactory</span></div><div class="line">    <span class="keyword">private</span> SqlSessionFactory sqlSessionFactory;</div><div class="line">    </div><div class="line">    <span class="meta">@Before</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUp</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">// 1 读取配置文件</span></div><div class="line">        String resource = <span class="string">"mybatis-config.xml"</span>;</div><div class="line">        InputStream inputStream = Resources.getResourceAsStream(resource);</div><div class="line">        <span class="comment">// 2 根据配置文件创建SqlSessionFactory</span></div><div class="line">        sqlSessionFactory = <span class="keyword">new</span> SqlSessionFactoryBuilder().build(inputStream);</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testFindUserById</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">// 创建SqlSession</span></div><div class="line">        SqlSession sqlSession = sqlSessionFactory.openSession();</div><div class="line">        <span class="comment">// 通过sqlSession，获取mapper接口的动态代理对象</span></div><div class="line">        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);</div><div class="line">        <span class="comment">// 调用mapper对象的方法</span></div><div class="line">        User user = userMapper.findUserById(<span class="number">1</span>);</div><div class="line">        System.out.println(user);</div><div class="line">        <span class="comment">// 关闭资源</span></div><div class="line">        sqlSession.close();</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testFindUsersByName</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">// 创建SqlSession</span></div><div class="line">        SqlSession sqlSession = sqlSessionFactory.openSession();</div><div class="line">        <span class="comment">// 通过sqlSession，获取mapper接口的动态代理对象</span></div><div class="line">        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);</div><div class="line">        <span class="comment">// 调用mapper对象的方法</span></div><div class="line">        List&lt;User&gt; list = userMapper.findUsersByName(<span class="string">"小明"</span>);</div><div class="line">        System.out.println(list);</div><div class="line">        <span class="comment">// 关闭资源</span></div><div class="line">        sqlSession.close();</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testInsertUser</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">// 创建SqlSession</span></div><div class="line">        SqlSession sqlSession = sqlSessionFactory.openSession();</div><div class="line">        <span class="comment">// 通过sqlSession，获取mapper接口的动态代理对象</span></div><div class="line">        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);</div><div class="line">        <span class="comment">// 调用mapper对象的方法</span></div><div class="line">        User user = <span class="keyword">new</span> User();</div><div class="line">        user.setUsername(<span class="string">"神奇的鸭鸭2"</span>);</div><div class="line">        user.setAddress(<span class="string">"计创南3002"</span>);</div><div class="line">        userMapper.insertUser(user);</div><div class="line">        <span class="comment">// 关闭资源</span></div><div class="line">        sqlSession.close();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-12-05T09:57:56.343Z" itemprop="dateUpdated">2017年12月5日 17:57</time>
</span><br>


        如要转载请注明出处：<a href="/2017/08/13/Mybatis_primary_02/" target="_blank" rel="external">http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/</a>
    </div>
    <footer>
        <a href="http://magic_duck.oschina.io">
            <img src="/img/avatar.jpg" alt="神奇的鸭鸭">
            神奇的鸭鸭
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/SSM/">SSM</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/&title=《Mybatis快速入门二(DAO开发思路)》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/&title=《Mybatis快速入门二(DAO开发思路)》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Mybatis快速入门二(DAO开发思路)》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/08/13/Mybatis_primary_03/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">Mybatis快速入门三(全局配置)</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/08/10/Mybatis_primary_01/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Mybatis快速入门一(基本应用)</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/z77z" target="_blank">邹海清</a></span>
            <span>神奇的鸭鸭の码农库 &copy; 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/&title=《Mybatis快速入门二(DAO开发思路)》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/&title=《Mybatis快速入门二(DAO开发思路)》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Mybatis快速入门二(DAO开发思路)》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://magic_duck.oschina.io/2017/08/13/Mybatis_primary_02/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
